/**
 * Created by kevin on 2017/7/26.
 */

let Applications = require('../models/Applications');
let Delegaters = require('../models/Delegaters');
let Packages = require('../models/Packages');
let DocClassifies = require('../models/DocClassifies');
let Docs = require('../models/Docs');

let push = require('../utils/push');
let fs = require('fs');
let stream = require('./stream');
let website = require('./website');
var scripter = require('./scripter');
let dingding = require('./dingding');


let archiveTool = {};

function scriptUrlCreate(req,type,prefix,suffix,name,url,branch,version,build,bundleId,id,cb,config,gitPath,teamId,sign) {
    prefix = prefix.replace(/\r\n/g,"&nbcl;");
    suffix = suffix.replace(/\r\n/g,"&nbcl;");
    prefix = prefix.replace(/\ +/g,"&nbsp;");
    suffix = suffix.replace(/\ +/g,"&nbsp;");
    var data = {
        'n' : name,
        'u' : url,
        'b' : branch,
        'v' : version,
        'bd' : build,
        'bi' : bundleId,
        'id' : id,
        'cb' : cb,
        'cf' : config,
        'prefix': prefix,
        'suffix': suffix,
        'gp' : gitPath
    };

    if (type === 'ios') {
        data.s = sign;
        data.ti = teamId;
    }
    let json = JSON.stringify(data);
    let buf = new Buffer(json);
    let base64 = buf.toString('base64');
    return urlJoinParam(req,type,base64);

}

function urlJoinParam(req,type,param) {
    return website.url(req) + '/script/' + type + '.sh\?c=' + param;
}

archiveTool.archiveIOS = function (req,uid,appId,delId,socketServer,cb) {
    let type = 1;
    Applications.getById(appId, function (err,app) {
        if (err) {
            if (cb) {
                cb(err,null);
            }
        } else  {
            if (!app) {
                if (cb) {
                    cb(new Error('应用不存在'),null);
                }
                return;
            }
            if (app.status === 1) {
                if (cb) {
                    cb(new Error('应用已经在打包'),null);
                }
                return;
            }
            Delegaters.getById(delId,function (err,delegater) {
                if (err) {
                    if (cb) {
                        cb(err,null);
                    }
                } else {
                    if (!delegater) {
                        if (cb) {
                            cb(new Error('代理机不存在'),null);
                        }
                    }
                    let packageObj = {
                        build : app.build,
                        version : app.version,
                        robots : app.robots,
                        branch : app.branch,
                        user : uid,
                        type : type,
                        delegater : delId,
                        app : appId,
                        status : 0
                    };

                    Packages.create(packageObj,function (err,p) {
                        if (err) {
                            if (cb) {
                                cb(err,null);
                            }
                        } else {
                            Applications.edit(appId,{status:1},function (err,data) {
                                if (err) {
                                    if (cb) {
                                        cb(err,null);
                                    }
                                } else  {
                                    if (cb) {
                                        cb(null,p._id);
                                    }
                                    // 通知开始打包
                                    if (app && app.robots) {
                                        Packages.getById(p._id,function (err,packageInfo) {
                                            app.robots.forEach(function (robot) {
                                                dingding.sendPackageStart(req,robot.token,data);
                                            })
                                        });
                                    }

                                    let startTime = new Date().getInterval();
                                    let writeStream = new stream.writeStream(1,type, app.bundleId + '_' + app.version + '_' + app.build + '.log');
                                    let gitUrl = app.gitlab;
                                    if (app.gitUser) {
                                        let gituser = app.gitUser;
                                        let urlComs = app.gitlab.split('//');
                                        let username = gituser.username;
                                        username = username.replace(/@/g,'%40');
                                        let passwd = gituser.passwd;
                                        passwd = passwd.replace(/@/g,'%40');
                                        gitUrl = urlComs[0] + '//' + username + ':' + passwd + '@' + urlComs[1];
                                    }
                                    let scriptUrl = scriptUrlCreate(req,'ios',delegater.prefixScript,delegater.suffixScript,app.projectName,gitUrl,app.branch,app.version,app.build,app.bundleId,p._id,website.url(req),app.configuration,app.gitPath,app.teamId,app.sign);
                                    let shell = `bash -c "$(curl -fsSL ${scriptUrl})"`;
                                    //let shell = "/Users/" + delegater.user + "/iPack/iOS/Scripts/archive.sh " + app.projectName + ' ' + gitUrl + ' ' + app.branch + ' ' + app.sign + ' ' + app.version + ' ' + app.build + ' ' + app.bundleId + ' ' + p._id + ' ' + website.url(req) + ' ' + app.configuration + ' ' + app.teamId + ' ' + app.gitPath;

                                    console.log('shell ' + shell);

                                    scripter.execute(shell,function (data) {
                                        if (data.indexOf('Receiving') !== 0) {
                                            writeStream.write(data);
                                        }
                                        socketServer.sendMessage('archive',app.name,{
                                            message : data
                                        });

                                    },function (data) {
                                        writeStream.write(data);
                                        socketServer.sendError('archive',app.name,{
                                            message : data
                                        });
                                    }, function (code) {
                                        let endDate = new Date();
                                        if (code === 0) {
                                            writeStream.write('打包完成');
                                            let endTime = endDate.getInterval();

                                            Applications.edit(app._id,{status:0,build:app.build+1,ptime:new Date()},function (err,d) {

                                            });
                                            Packages.edit(p._id,{status : 1},function (err,data) {
                                                if (err) {

                                                } else  {
                                                    if (app && app.robots) {
                                                        Packages.getById(p._id,function (err,packageInfo) {
                                                            app.robots.forEach(function (robot) {
                                                                dingding.sendPackageSuccess(req,robot.token,packageInfo);
                                                            })
                                                        });
                                                    }
                                                    // 删除日志
                                                    let logAddress = 'data/log/packages/ios/' + p.app.bundleId + "_" + p.version + '_' + p.build + '.log';
                                                    if (fs.existsSync(logAddress)) {
                                                        fs.unlinkSync(logAddress);
                                                    }

                                                    let spendTime = endTime - startTime;
                                                    let totalSpend = delegater.packageSpend + spendTime;
                                                    let totalCount = delegater.packageCount + 1;
                                                    let avageSpend = parseInt(totalSpend / totalCount);
                                                    Delegaters.edit(delId,{packageCount:totalCount,packageSpend:avageSpend},function (err,delInfo) {
                                                        console.log(err + delInfo);
                                                    });
                                                    //push.pushIOS(app.name+'有新包啦',{type:1,id:p._id},function (err,result) {

                                                    //});
                                                    // 写入文章
                                                    let docClassify = DocClassifies.getByName('打包资讯',function (e,c) {
                                                        if (e) {} else {
                                                            let doc = {
                                                                name : app.name + 'iOS' + '（' + app.version + '.' + app.build + '）' + '已打包',
                                                                classify : c._id,
                                                                updateUser : uid,
                                                                createUser : uid,
                                                                content : 'ipack://package/download/' + p._id,
                                                                weight : '4'
                                                            };
                                                            Docs.createUniqueName(doc);
                                                        }
                                                    });

                                                    socketServer.sendMessage('archive',app.name,{
                                                        message : 'ipack'
                                                    });
                                                }
                                            });

                                        } else {
                                            writeStream.write('打包失败');
                                            Applications.edit(app._id,{status:-1,build:app.build+1},function (err,d) {

                                            });

                                            Packages.edit(p._id,{status : -1},function (err,data) {
                                                if (err) {

                                                } else  {

                                                }
                                            });
                                            socketServer.sendError('archive',app.name,{
                                                message : 'ipack'
                                            });
                                        }

                                    } ,delegater.user+'@'+delegater.ip);
                                }
                            });
                        }
                    });
                }
            });
        }
    });
};

archiveTool.archiveAndroid = function (req,uid,appId,delId,socketServer,cb) {
    let type = 2;
    Applications.getById(appId, function (err,app) {
        if (err) {
            if (cb) {
                cb(err,null);
            }
        } else  {
            if (!app) {
                if (cb) {
                    cb(new Error('应用不存在'),null);
                }
                return;
            }
            if (app.status === 1) {
                if (cb) {
                    cb(new Error('应用已经在打包'),null);
                }
                return;
            }
            Delegaters.getById(delId,function (err,delegater) {
                if (err) {
                    if (cb) {
                        cb(err,null);
                    }
                } else {
                    if (!delegater) {
                        if (cb) {
                            cb(new Error('代理机不存在'),null);
                        }
                    }
                    let packageObj = {
                        build : app.build,
                        version : app.version,
                        robots : app.robots,
                        branch : app.branch,
                        user : uid,
                        type : type,
                        delegater : delId,
                        app : appId,
                        status : 0
                    };

                    Packages.create(packageObj,function (err,p) {
                        if (err) {
                            if (cb) {
                                cb(err,null);
                            }
                        } else {
                            Applications.edit(appId,{status:1},function (err,data) {
                                if (err) {
                                    if (cb) {
                                        cb(err,null);
                                    }
                                } else  {
                                    if (cb) {
                                        cb(null,p._id);
                                    }
                                    // 通知开始打包
                                    if (app && app.robots) {
                                        Packages.getById(p._id,function (err,packageInfo) {
                                            app.robots.forEach(function (robot) {
                                                dingding.sendPackageStart(req,robot.token,data);
                                            })
                                        });
                                    }

                                    let startTime = new Date().getInterval();
                                    let writeStream = new stream.writeStream(1,type, app.bundleId + '_' + app.version + '_' + app.build + '.log');
                                    let gitUrl = app.gitlab;
                                    if (app.gitUser) {
                                        let gituser = app.gitUser;
                                        let urlComs = app.gitlab.split('//');
                                        let username = gituser.username;
                                        username = username.replace(/@/g,'%40');
                                        let passwd = gituser.passwd;
                                        passwd = passwd.replace(/@/g,'%40');
                                        gitUrl = urlComs[0] + '//' + username + ':' + passwd + '@' + urlComs[1];
                                    }

                                    // let platformP = delegater.platform === 1 ? '/Users/' : '/home/';
                                    let scriptUrl = scriptUrlCreate(req,'android',delegater.prefixScript,delegater.suffixScript,app.projectName,gitUrl,app.branch,app.version,app.build,app.bundleId,p._id,website.url(req),app.configuration,app.gitPath);
                                    let shell = `sh -c "$(curl -fsSL ${scriptUrl})"`;
                                    // var shell = platformP + delegater.user + "/iPack/Android/Scripts/archive.sh " + app.projectName + ' ' + gitUrl + ' ' + app.branch + ' ' + app.configuration + ' ' + app.version + ' ' + app.build + ' ' + app.bundleId + ' ' + p._id + ' ' + website.url(req) + ' ' + app.gitPath;
                                    console.log('shell ' + shell);

                                    scripter.execute(shell,function (data) {
                                        if (data.indexOf('Receiving') !== 0) {
                                            writeStream.write(data);
                                        }
                                        socketServer.sendMessage('archive',app.name,{
                                            message : data
                                        });

                                    },function (data) {
                                        writeStream.write(data);
                                        socketServer.sendError('archive',app.name,{
                                            message : data
                                        });
                                    }, function (code) {
                                        let endDate = new Date();
                                        if (code === 0) {
                                            writeStream.write('打包完成');
                                            let endTime = endDate.getInterval();

                                            Applications.edit(app._id,{status:0,build:app.build+1,ptime:new Date()},function (err,d) {

                                            });
                                            Packages.edit(p._id,{status : 1},function (err,data) {
                                                if (err) {

                                                } else  {
                                                    if (app && app.robots) {
                                                        Packages.getById(p._id,function (err,packageInfo) {
                                                            app.robots.forEach(function (robot) {
                                                                dingding.sendPackageSuccess(req,robot.token,packageInfo);
                                                            })
                                                        });
                                                    }
                                                    // 删除日志
                                                    let logAddress = 'data/log/packages/android/' + p.app.bundleId + "_" + p.version + '_' + p.build + '.log';
                                                    if (fs.existsSync(logAddress)) {
                                                        fs.unlinkSync(logAddress);
                                                    }

                                                    let spendTime = endTime - startTime;
                                                    let totalSpend = delegater.packageSpend + spendTime;
                                                    let totalCount = delegater.packageCount + 1;
                                                    let avageSpend = parseInt(totalSpend / totalCount);
                                                    Delegaters.edit(delId,{packageCount:totalCount,packageSpend:avageSpend},function (err,delInfo) {
                                                        console.log(err + delInfo);
                                                    });
                                                    push.pushAndroid(app.name+'有新包啦',app.name+'有新包啦',{type:1,id:p._id},function (err,result) {

                                                    });
                                                    // 写入文章
                                                    let docClassify = DocClassifies.getByName('打包资讯',function (e,c) {
                                                        if (e) {} else {
                                                            let doc = {
                                                                name : app.name + 'Android' + '（' + app.version + '.' + app.build + '）' + '已打包',
                                                                classify : c._id,
                                                                updateUser : uid,
                                                                createUser : uid,
                                                                content : 'ipack://package/download/' + p._id,
                                                                weight : '4'
                                                            };
                                                            Docs.createUniqueName(doc);
                                                        }
                                                    });

                                                    socketServer.sendMessage('archive',app.name,{
                                                        message : 'ipack'
                                                    });
                                                }
                                            });

                                        } else {
                                            writeStream.write('打包失败');
                                            Applications.edit(app._id,{status:-1,build:app.build+1},function (err,d) {

                                            });

                                            Packages.edit(p._id,{status : -1},function (err,data) {
                                                if (err) {

                                                } else  {

                                                }
                                            });
                                            socketServer.sendError('archive',app.name,{
                                                message : 'ipack'
                                            });
                                        }

                                    } ,delegater.user+'@'+delegater.ip);
                                }
                            });
                        }
                    });
                }
            });
        }
    });
};

module.exports = archiveTool;